using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using Quiki.ExpressionParsers;
using Quiki.Helpers;

namespace Quiki.ElementFormatters
{
    public class PreElementFormatter : ElementFormatterBase
    {
        public override bool FormatBegin(WikiTextElement element, HtmlFormatterContext context)
        {
            if (element.ElementType != WikiTextElementType.Pre)
                return false;

            if (context.CurrentParagraphType != WikiTextElementType.Pre)
            {
                context.CloseAllParagraphs ();
                context.CurrentParagraphType = WikiTextElementType.Pre;
                context.PushTag (HtmlTextWriterTag.Pre);
                context.SuppressTabs ();
            }
            else
            {
                context.SuppressTabs ();
                context.Writer.WriteLine ();
            }

            return true;
        }

        public override void FormatText (WikiTextElement element, HtmlFormatterContext context)
        {
            string trimmedLines = TrimExcessEmptyLines(element.Text);

            context.Writer.Write (HttpUtility.HtmlEncode (trimmedLines));
        }

        public override void FormatEnd (WikiTextElement element, HtmlFormatterContext context)
        {
            context.ResumeTabs ();
        }

        private static string TrimExcessEmptyLines(string text)
        {
            IList<string> lines = text.SplitIntoLines();

            if (lines.Count == 1)
                return text.TrimEnd();

            int i;
            for (i = lines.Count-1; i >= 0; i--)
            {
                if (lines[i].Trim().Length > 0)
                    break;
            }

            if (i < 0)
                return text;

            return StringEx.JoinLines(lines, 0, i+1);
        }
    }
}